//
//  XDOAuthController.swift
//  weibo
//
//  Created by lucy on 2016/10/23.
//  Copyright © 2016年 com.huashengHuaSheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class XDOAuthController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    //懒加载webView
    private lazy var webView : UIWebView = {
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(XDAPPKEY)&redirect_uri=\(XDREDIRECTURI)")!
        let request = URLRequest(url: url)
        let view = UIWebView()
        view.delegate = self
        view.loadRequest(request)
    
        return view
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()

        
    }
    
    
    //MARK-设置UI
    private func setupUI(){
    
        view.backgroundColor = UIColor.white
        setupNav()
        
    
    }
    
    
    
    //MARK-取消按钮点击
    @objc private func cancelClick(){
        
        dismiss(animated: true, completion: nil)
    }
    

    //MARK-自动填充按钮点击
    @objc private func autoFillClick(){
//        print("自动填充")
        let jsonStr =  "document.getElementById('userId').value='\(XDUSERACCOUNT)',document.getElementById('passwd').value='\(XDUSERPWD)'"
        webView.stringByEvaluatingJavaScript(from: jsonStr)

    }
    
    
    
    //MARK-设置导航控制器
    private func setupNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(setHighlightImgName: nil, title:"取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(setHighlightImgName: nil, title: "自动填充", target: self, action: #selector(autoFillClick))
        navigationItem.title = "微博登录"
        
    
    }
}



//MARK-UIWebViewDelegate webView的代理
extension XDOAuthController: UIWebViewDelegate{
    
    //- 监听webView 将要加载的request 默认不实现 返回的是 true
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool  {
        
        let urlStr = request.url?.absoluteString
        if let u = urlStr, u.hasPrefix(XDREDIRECTURI){
        
            let query = request.url?.query
            if let q = query{
            
                let code = q.substring(from: "code=".endIndex)
                print("----",code)
                XDUserAccountViewModel.shareTools.getUserAccount(code: code, finish: { (isSuccess) in
                    if(!isSuccess){
                        print("请求失败")
                        SVProgressHUD.showError(withStatus: "请求失败")
                        return
                    
                    }
                    print("请求成功")
                    SVProgressHUD.dismiss()
                    self.dismiss(animated: false, completion: { 
                        
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: XDSWITCHVCNOTI), object: nil)
                    })
                })
                return false

            }
        
        }
        
        return true
        
        //将要加载
        func webViewDidStartLoad(_ webView:UIWebView){
        
            SVProgressHUD.show()
        }
        
        //完成加载
        func webViewDidFinishLoad(_ webView:UIWebView){
        
            SVProgressHUD.dismiss()
        }
        
        //出现错误
        func webView(_ webView : UIWebView, didFailLoadWithError error:Error){
        
        
        }
    }

}





















